import { createCategory, getCategories } from "@src/services/categories";
import validate from "@src/util/validate";
import { NextFunction, Response, Request } from "express";
import { Schema } from "express-validator";

/* ------------------------------- Validators ------------------------------- */
const categoriesSchema: Schema = {
  title: {
    isString: true,
    isLength: {
      options: { min: 2, max: 20 },
    },
    notEmpty: true,
    trim: true,
    errorMessage: 'title 必须是字符串，长度在2-20个字符之间'
  },
}


/* -------------------------------- Function -------------------------------- */

export const getAllCategories = async (req: Request, res: Response, next: NextFunction) => {
  const result = await getCategories();
  res.status(200).json(result);
}

export const addCategory = async (req: Request, res: Response, next: NextFunction) => {
  const { title } = req.body;

  const errors = await validate(req, res, categoriesSchema);
  if (errors) {
    req.flash('error', '分类添加失败：' + JSON.stringify(errors));
    return res.redirect('/categories/add');
  }

  try {
    const result = await createCategory(title);
    req.flash('success', '分类添加成功！');
    return res.redirect('/categories/add');
  } catch (error: any) {
    req.flash('error', '分类添加失败：' + error.message);
    return res.redirect('/categories/add');
  }
}
